<template>
    <div class="Cate-container">
         <!-- 导航区域 -->
         <el-breadcrumb separator-class="el-icon-arrow-right">
           <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
           <el-breadcrumb-item>权限管理</el-breadcrumb-item>
           <el-breadcrumb-item>角色列表</el-breadcrumb-item>
         </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
    <!-- 添加按钮 -->
    <el-row>
        <el-button type="primary" class="add_category" @click="btndialogVisible">添加分类</el-button>
    </el-row>

    <!-- 表格 -->
    <tree-table border  :data="catelist" :columns="columns" :selection-type="false" :expand-type="false" show-index
      index-text="序号">
        <template slot="isok" slot-scope="scope">
            <i class="el-icon-success" v-if="scope.row.cat_pid === 0"></i>
            <i class="el-icon-error" v-else></i>
        </template>

        <template slot="rank" slot-scope="scope">
            <el-tag type="primary" v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag type="warning" v-else-if="scope.row.cat_level === 1">二级</el-tag>
            <el-tag type="warning" v-else>三级</el-tag>
        </template>

        <template slot="operating" slot-scope="scope">
             <el-button type="primary" size="small" icon="el-icon-edit">编辑</el-button>
             <el-button type="danger" size="small" icon="el-icon-delete">删除</el-button>
        </template>
    </tree-table>
    
        <!-- 分页功能 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="querInfo.pagenum" :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="dialogVisible" width="50%" @close="closeForm">

        <el-form :model="addCategory" :rules="rules" ref="ruleForm" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCategory.cat_name"></el-input>
          </el-form-item>

          <el-form-item label="父级分类">
              <el-cascader v-model="parentLevel" expandTrigger='hover' :options="parentclassification"
                :props="expandTrigger" @change="handleChange" size="small" clearable></el-cascader>
          </el-form-item>
        </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adddialogVisible">确 定</el-button>
      </span>
    </el-dialog>

    </div>
</template>


<script>
export default {
    data(){
        return{
            querInfo:{
                type:3,
                pagenum: 1,
                pagesize: 5
            },
            catelist:[],
            total:0,
            // 表格各列的数据
            columns:[{
                label:"分类名称",
                prop:'cat_name',
            },{
                label:"是否有效",
                type: 'template',
                template: 'isok',
            },{
                label:"排序",
                type: 'template',
                template: 'rank',
            },{
                label:"操作",
                type: 'template',
                template: 'operating',
            }
            ],
            dialogVisible: false,
            
            addCategory:{
                //添加分类的名字
                cat_name:'',
                //父级分类的ID
                cat_pid:0,
                // 分类的层级
                cat_level:0
                 
            },
            // 添加验证规则
            rules: {
            cat_name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
            ]
            },

            // 父级分类的列表
           parentclassification:[],
          
            //级联选择器的选项
           expandTrigger: {
               value:'cat_id',
               label:'cat_name',
               children:'children',
               checkStrictly:'true'
           },
           
           parentLevel:[]
        }
    },

    // 生命周期
    created(){
        this.getCateList()
  },


    // 方法
    methods:{
        // 获取商品分类数据
      async getCateList(){
           const {data: res}  = await this.$http.get('categories',{params:this.querInfo})

            if(res.meta.status !== 200){
               return this.$message.error('获取数据失败')
            }
// console.log(res.data);
            this.catelist = res.data.result
            this. total = res.data. total
          
        },

        btndialogVisible(){
            this.getparentclassification()
            this.dialogVisible = true
        },

        // 分页区域
        handleSizeChange(newSize){
            this.querInfo.pagesize = newSize
            this.getCateList()
        },
        handleCurrentChange(newNum){
            this.querInfo.pagenum = newNum
            this.getCateList()
        },

        // 获取父级分类的列表
       async getparentclassification(){
          const{data: res} =await this.$http.get('categories',{params:{type:2}})
          if(res.meta.status !== 200){
             return this.$message.error('创建父级分类失败')
          }
            this.parentclassification = res.data
            // console.log(res.data);
        },
        
        handleChange(){
            // 如果数组中的长度(就是级联选择器中的v-modle)大于0了，则选中的是父级分类，即添加的是二级标签，若等于零就是一级标签
            if(this.parentLevel.length > 0){
                // 父级分类的id
               this.addCategory.cat_pid = this.parentLevel[this.parentLevel.length - 1]
               this.addCategory.cat_level = this.parentLevel.length
               return 
            }else {
                 this.addCategory.cat_pid = 0
                 this.addCategory.cat_level = 0
            }
        },

            adddialogVisible(){
                this.$refs.ruleForm.validate(async valid => {  //validate 是什么意思？
                if(!valid)return 
                  const{data:res} =  await this.$http.post('categories',this.addCategory)
                    
                       if(res.meta.status !==201){
                       return this.$message.error('失败')
                       }
                        this.$message.success('成功')
                        this.getCateList()
                        this.getparentclassification()
                        this.dialogVisible = false //确认按钮之后关闭显示框
                })
            },

        // 监听对话框的关闭事件，重置表单
        closeForm (){
             this.$refs.ruleForm.resetFields()
             this.parentLevel = []
             this.cat_name = ''
             this.cat_level = ''
            },
   
    },

}
</script>


<style lang="less" scoped>
    .add_category {
        margin-bottom: 15px;
    }

    .el-pagination {
        margin-top: 10px;
    }

    .el-cascader {
        width:100%;
    }
</style>